package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Viper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IViperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员Controller
 *
 * @author ...
 * @date 2022-03-17
 */
@RestController
@RequestMapping("/system/viper")
public class ViperController extends BaseController {
    @Autowired
    private IViperService viperService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询会员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Viper viper) {
        startPage();
        List<Viper> list = viperService.selectViperList(viper);
        return getDataTable(list);
    }

    /**
     * 获取会员详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:viper:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(viperService.selectViperById(id));
    }

    /**
     * 新增会员
     */
    @PostMapping
    public AjaxResult add(@RequestBody Viper viper) {
        // 判断当前用户是否是会员
        viper.setUid(SecurityUtils.getUserId().intValue());
        List<Viper> vipers = viperService.selectViperList(viper);
        Assert.isTrue(vipers.size()==0,"您已经是会员");
        viper.setCreateUser(SecurityUtils.getUserId().intValue());
        viper.setCreateTime(DateUtils.getNowDate());
        viper.setUid(SecurityUtils.getUserId().intValue());
        viper.setUname(SecurityUtils.getLoginUser().getUser().getNickName());
        SysUser sysUser = new SysUser();
        sysUser.setUserId(viper.getUid().longValue());
        sysUser.setRemark("会员");
        // 修改用户表标示
        userService.updateUser(sysUser);
        viper.setCreateUser(SecurityUtils.getUserId().intValue());
        viper.setCreateTime(DateUtils.getNowDate());
        return toAjax(viperService.insertViper(viper));
    }

    /**
     * 修改会员
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Viper viper) {
        viper.setUpdateUser(SecurityUtils.getUserId().intValue());
        viper.setUpdateTime(DateUtils.getNowDate());
        return toAjax(viperService.updateViper(viper));
    }

    /**
     * 删除会员
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(viperService.deleteViperByIds(ids));
    }
}
